import random
import re

from django.contrib.auth.hashers import check_password, make_password

from libs.yzk_jwt import TokenManager
# from user.models import User
# from user.models import User
from .models import User
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.views import obtain_jwt_token  # 导入token签发认证的入口
from django.db.models import Q
from rest_framework.exceptions import APIException, ValidationError
from django.conf import settings
from django.core.cache import cache
# from faker import Faker

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class LoginSerializer(serializers.ModelSerializer):
    username = serializers.CharField(required=False)
    password = serializers.CharField(required=False)
    phone = serializers.CharField(required=False)
    # sex = serializers.CharField(source='get_user_type_display')
    number = [3]

    class Meta:
        model = User
        fields = ['username', 'password', 'phone']

    # def _get_token(self, user):
    #     try:
    #         payload = jwt_payload_handler(user)
    #         token = jwt_encode_handler(payload)
    #         return token
    #     except Exception as e:
    #         raise ValidationError(e)
    def _get_user(self, attrs):
        import re
        username = attrs.get('username')
        try:
            user = User.objects.all().get(username=username)
        except Exception as e:
            raise APIException('user not exist')
        # if re.match(r'^1[3-9][0-9]{9}$', username):
        #     print(111)
        #     user = User.objects.filter(phone=username).first()
        # else:
        #     user = User.objects.filter(username=username).first()
        if not user:
            raise APIException(detail='用户名错误')
        password = attrs.get('password')
        # if not user.check_password(password):
        if password != user.password:
            # raise APIException(detail='密码错误')
            # if user and not check_password(password,user.password):
            if self.number[0] > 0:
                print('111>>>>>>>>>>>>>>>>')
                output = f'用户名或者密码错误，你还有{self.number[0]}次机会'
                print(self.number[0])
                self.number[0] -= 1
                raise APIException(output)
            else:
                print('222222222222>>>>>>>>>>>>>>')
                User.objects.all().filter(username=username).update(is_active=0)
                raise APIException('你已经输错三次密码，请等待管理员激活！')
        # if not user.is_active:
        #     raise APIException(detail='您已被锁定，不能登录')
        return user

    def _get_token(self, user):
        token = TokenManager.get_token(user)
        return token

    def validate(self, attrs):
        user = self._get_user(attrs)
        # user签发token
        token = self._get_token(user)
        self.context['id'] = user.id
        self.context['token'] = token
        self.context['username'] = user.username
        # self.context['icon'] = 'http://127.0.0.1:8000/media/' + str(user.icon)

        user_info = {'name': user.username,
                     # 'phone': user.phone,
                     'user_id': user.id,
                     # 'user_type':user.user_type,
                     # 'user_type_name': user.get_user_type_display(),  # 获取用户类型的中文显示
                     # 'team_id': user.team.id,
                     # 'team_name': user.team.name,
                     # 'icon':self.context['icon']}
                     }
        self.context['user_info'] = user_info

        return attrs